import json
import sys


if __name__ == "__main__":
    if len(sys.argv) < 3:
        print("Usage: python3 convert_grafana_dashboard.py infile outfile")
        sys.exit(1)
    infile = sys.argv[1]
    outfile = sys.argv[2]
    output_json = {"dashboard": {}}
    with open(infile, "r") as f:
        data = json.load(f)
        output_json["dashboard"] = data
        for panel in data["panels"]:
            if "datasource" in panel and not isinstance(panel["datasource"], str):
                panel["datasource"] = f"sysom-{panel['datasource']['type']}"
            if "targets" in panel:
                for item in panel["targets"]:
                    if "datasource" in item and not isinstance(item["datasource"], str):
                        item["datasource"] = f"sysom-{item['datasource']['type']}"
        for item in data["templating"]["list"]:
            if "datasource" in item and not isinstance(item["datasource"], str):
                item["datasource"] = f"sysom-{item['datasource']['type']}"
                
        data["id"] = None
        data["editable"] = False

    with open(outfile, "w") as f:
        json.dump(output_json, f, indent=4)
